package com.leyou.sms.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.sms.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class SmsUtil {

    @Autowired
    private IAcsClient acsClient;
    @Autowired
    private SmsProperties prop;

    /**
     * 发送短信验证码
     * @param phone 手机号
     * @param code 验证码
     */
    public void sendVerifyCode(String phone, String code){
        try {
            // 格式化参数
            String param = String.format("{\"code\":\"%s\"}", code);
            // 发送短信验证码
            sendMessage(phone, prop.getSignName(), prop.getVerifyCodeTemplate(), param);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通用发送短信的工具类
     * @param phone 电话
     * @param signName 签名
     * @param templateCode 模板
     * @param templateParam 模板参数
     */
    public void sendMessage(String phone, String signName, String templateCode, String templateParam) {
        // 准备短信发送的请求
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(prop.getDomain());
        request.setSysVersion(prop.getVersion());
        request.setSysAction(prop.getAction());
        request.putQueryParameter("RegionId", prop.getRegionID());
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", templateParam);
        try {
            CommonResponse response = acsClient.getCommonResponse(request);
            // 解析结果
            Map<String, String> data = JsonUtils.toMap(response.getData(), String.class, String.class);
            // 判断结果
            if (!"OK".equals(data.get("Code"))) {
                // 失败
                log.error("短信发送失败！原因：{}", data.get("Message"));
                throw new LyException(500, "短信发送失败！");
            }
            // 发送成功
            log.info("发送短信成功！");
        } catch (ServerException e) {
            log.error("发送短信失败，服务端异常：", e);
            throw new RuntimeException(e);
        } catch (ClientException e) {
            log.error("发送短信失败，客户端异常：", e);
            throw new RuntimeException(e);
        }
    }
}
